#!/usr/bin/python

"""
    Class: Logger, a class which log program events
"""

import collections
import json
import logging
import socket
import time

class EventLogger(object):
    """
    _logger_file: specified log file path
    """
    _logger_file      = ""

    """
    _logger_name: logger name of event logger
    """
    _logger_name      = "EventLogger"

    """
    _unix_socket_path: unix socket path
    """
    _unix_socket_path = ""

    """
    _log_sequence: log message sequence
    """
    _log_sequence     = None

    """
    constructor: initialize logger
    """
    def __init__(self):
        super(EventLogger, self).__init__()
        return


    """
    set_logger: set logger with base configuration
    """
    def set_logger(self, logger_file, logger_name, unix_socket_path):
        ret = True
        try:
            if logger_file is not None and len(logger_file):
                self._logger_file = logger_file
            if logger_name is not None and len(logger_name):
                self._logger_name = logger_name
            if unix_socket_path is not None and len(unix_socket_path):
                self._unix_socket_path = unix_socket_path
            self._log_sequence = collections.deque()
        except TypeError:
            self._clean_up_logger()
            ret = False
        return ret


    """
    _clean_up_logger: clean up logger
    """
    def _clean_up_logger(self):
        if self._log_sequence is not None and len(self._log_sequence):
            sock     = None
            push_obj = {"logger":self._logger_name, "file_name":self._logger_file, "message":list(self._log_sequence)}
            try:
                sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
                sock.connect(self._unix_socket_path)
                sock.send(json.dumps(push_obj) + "\r\n\r\n")
                response = sock.recv(256)
            except socket.error,e:
                print ("[Core][EventLogger]Connect to unix socket %s error, system error message %s" % (self._unix_socket_path, str(e)))
            finally:
                if sock is not None:
                    sock.close()
            self._log_sequence.clear()
        return


    """
    clean: clean up logger by outer caller
    """
    def clean(self):
        self._clean_up_logger()
        return


    """
    _create_time_string: create timer string
    """
    def _create_time_string(self):
        return time.strftime("%Y-%m-%d %H:%M:%S %Z")

    """
    log_error: log error info
    """
    def log_error(self, message):
        if message is not None and len(message):
            self._log_sequence.append({"time":self._create_time_string(), "level":logging.ERROR, "message":message})
        return


    """
    log_info: log normal info
    """
    def log_info(self, message):
        if message is not None and len(message):
            self._log_sequence.append({"time":self._create_time_string(), "level":logging.INFO, "message":message})
        return


    """
    log_debug: log debug info
    """
    def log_debug(self, message):
        if message is not None and len(message):
            self._log_sequence.append({"time":self._create_time_string(), "level":logging.DEBUG, "message":message})
        return


    """
    log_warning: log warning info
    """
    def log_warning(self, message):
        if message is not None and len(message):
            self._log_sequence.append({"time":self._create_time_string(), "level":logging.WARNING, "message":message})
        return


    """
    log_critial: log critical error info
    """
    def log_critical(self, message):
        if message is not None and len(message):
            self._log_sequence.append({"time":self._create_time_string(), "level":logging.CRITICAL, "message":message})
        return

if __name__ == "__main__":
    event_logger = EventLogger()
    event_logger.set_logger("/home/event.log", "EVENTLOGGER", "/home/logger.sock")
    event_logger.log_error("how about log here!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
    event_logger.clean()
